/**
 * 
 */
package com.acxiom.bsh.service.impl;

import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acxiom.bsh.constants.ThreadLocalContextHolder;
import com.acxiom.bsh.dao.CommoDao;
import com.acxiom.bsh.dao.LuckyDrawDouble11Dao;
import com.acxiom.bsh.entity.DrawDouble11Result;
import com.acxiom.bsh.entity.DrawResult;
import com.acxiom.bsh.exception.BshException;
import com.acxiom.bsh.exception.ExceptionBuilder;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.pojo.Double11Prize;
import com.acxiom.bsh.pojo.Double11PrizeRecord;
import com.acxiom.bsh.pojo.Prize;
import com.acxiom.bsh.request.PointRequest;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.service.LuckyDrawDouble11Service;

/**
 * @Description: TODO
 * @author jerche
 *
 * @updateUser
 * @updateDate
 */
@Service
public class LuckyDrawDouble11ServiceImpl implements LuckyDrawDouble11Service {

	@Autowired
	private CommoDao commonDao;

	@Autowired
	LuckyDrawDouble11Dao drawDouble11Dao;

	@Autowired
	ApiService apiService;

	@Override
	public DrawDouble11Result double11Draw(String mixnick) throws BshException {
		DrawDouble11Result result = new DrawDouble11Result();
		if (!validateDrawTimes(mixnick, result)) {
			return result;
		}
		Double11Prize prize = draw(mixnick, result);

		reducePoint(mixnick, result);
		if (!result.isSuccess()) {
			return result;
		}

		if (prize.getGiftType() == 1) {
			addPoint(mixnick, prize.getPointCode(), result);
			if (!result.isSuccess()) {
				return result;
			}
		}
		return result;
	}

	@Override
	public List<Double11PrizeRecord> getDouble11PrizeList(String mixnick) {
		List<Double11PrizeRecord> prizeRecords = null;
		try {
			prizeRecords = drawDouble11Dao.getDouble11PrizeRecord(mixnick);
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services Double11PrizeRecord error", e);
		}
		return prizeRecords;
	}

	/**
	 * validate current day draw times, can not exceed the max draw times
	 * 
	 * @param mixNick
	 * @param result
	 * @return
	 * @throws BshException
	 */
	private boolean validateDrawTimes(String mixNick, DrawDouble11Result result) throws BshException {

		try {
			int drawDailyTimes = Integer.parseInt(commonDao.getSparameter("DOUBLE11_DRAW_DAILY_TIMES"));

			int currentDayDrawTimes = drawDouble11Dao.getCurrentDayDrawTimes(mixNick);
			if (currentDayDrawTimes >= drawDailyTimes) {
				result.setSuccess(false);
				result.setCode("001");
				result.setMessage("亲,您的抽奖次数已用完!");
				return false;
			}
			return true;
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services validateDrawTimes error", e);
			throw ExceptionBuilder.buildException("092", "当前系统繁忙，请稍后再试", e);
		}
	}

	/**
	 * validate weekly validate1234PrizeTimes times, can not exceed the max draw times
	 * 
	 * @param mixNick
	 * @param result
	 * @return
	 * @throws BshException
	 */
	private boolean validate1234PrizeDouble12Times(String mixNick, DrawDouble11Result result, Double11Prize prize) throws BshException {

		try {
			int drawWeeklyTimes = Integer.parseInt(commonDao.getSparameter("1234_DOUBLE12_DRAW_WEEKLY_TIMES"));

			int weeklyDrawTimes = drawDouble11Dao.get1234PrizeDouble12Times(mixNick, prize.getPrizeLevel());
			if (weeklyDrawTimes >= drawWeeklyTimes) {
				return false;
			}
			return true;
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("Services validate1234PrizeTimes error", e);
			throw ExceptionBuilder.buildException("092", "当前系统繁忙，请稍后再试", e);
		}
	}

	private Double11Prize draw(String mixNick, DrawDouble11Result result) throws BshException {
		Double11Prize resultPrize = null;
		try {
			Random rand = new Random();
			double num = rand.nextDouble();
			double lastProbability = 0;
			double currentProbability = 0;
			double nextProbability = 0;

			List<Double11Prize> prizeList = drawDouble11Dao.getDouble11Prize();
			for (Double11Prize prize : prizeList) {
				currentProbability = prize.getProbability();
				nextProbability = lastProbability + currentProbability;
				if (prize.getPrizeLevel() == 1 || prize.getPrizeLevel() == 2 || prize.getPrizeLevel() == 3 || prize.getPrizeLevel() == 4 ) {
					if (!validate1234PrizeDouble12Times(mixNick, result, prize)) {
						continue;
					}
				}

				if (num >= lastProbability && num < nextProbability) {
					lastProbability = nextProbability;
					num = nextProbability;
					int updateSize = drawDouble11Dao.updateInventory(prize);
					if (updateSize == 0) {
						continue;
					} else {
						drawSuccess(result, prize);
						Double11PrizeRecord record = new Double11PrizeRecord();
						record.setMixNick(mixNick);
						record.setPrizeId(prize.getId());
						record.setPrizeName(prize.getGiftName());
						String sellerName=URLDecoder.decode(ThreadLocalContextHolder.get().getValue(), "UTF-8");
						record.setSellerName(sellerName);
						drawDouble11Dao.saveDouble11PrizeRecord(record);

						resultPrize = prize;
						break;
					}
				}
				lastProbability = lastProbability + currentProbability;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("097", "当前系统繁忙，请稍后再试", e);
		}

		try {
			if (resultPrize == null) {
				resultPrize = drawDouble11Dao.getDefaultDouble11Prize();
				drawDouble11Dao.updateInventory(resultPrize);
				Double11PrizeRecord record = new Double11PrizeRecord();
				record.setMixNick(mixNick);
				record.setPrizeId(resultPrize.getId());
				record.setPrizeName(resultPrize.getGiftName());
				String sellerName=ThreadLocalContextHolder.get().getValue();
				record.setSellerName(sellerName);
				drawDouble11Dao.saveDouble11PrizeRecord(record);
				drawSuccess(result, resultPrize);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LoggerManager.getErrorLogger().error("getDefaultPrize  Prize Error", e);
			throw ExceptionBuilder.buildException("098", "当前系统繁忙，请稍后再试", e);
		}
		return resultPrize;
	}

	private void drawSuccess(DrawDouble11Result result, Double11Prize prize) {
		result.setSuccess(true);
		result.setPrizeLevel(prize.getPrizeLevel());
		result.setPrizeName(prize.getGiftName());
		result.setPrizeDescription(prize.getGiftDescription());
	}

	private void addPoint(String mixNick, String pointCode, DrawDouble11Result result) throws BshException {

		PointRequest request = new PointRequest();
		request.setEventCode(pointCode);
		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());
		request.setEventMemo("Lucky Draw add Points");

		ApiResponse response = null;
		try {
			response = point(request);
			if (response == null) {
				throw ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试");
			}
		} catch (BshException e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("0096", "当前系统繁忙，请稍后再试", e);
		}

	}

	private void reducePoint(String mixNick, DrawDouble11Result result) throws BshException {
		String pointCode = commonDao.getSparameter("LUCKY_DRAW_POINT_CODE");

		PointRequest request = new PointRequest();
		request.setEventCode(pointCode);
		request.setMix_taobaoId(mixNick);
		request.setiSN(System.currentTimeMillis());
		request.setEventMemo("Lucky Draw add Points");

		ApiResponse response = null;
		try {
			response = point(request);
			if (response == null) {
				throw ExceptionBuilder.buildException("095", "当前系统繁忙，请稍后再试");
			}
		} catch (BshException e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("094", "当前系统繁忙，请稍后再试", e);
		}

	}

	private ApiResponse point(PointRequest request) throws BshException {

		ApiResponse response = null;
		try {
			response = apiService.post("point", request);

		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("093", "当前系统繁忙，请稍后再试", e);
		}
		return response;
	}

	@Override
	public List<Double11PrizeRecord> getDouble11PrizeTop5() throws BshException {
		List<Double11PrizeRecord> prizeTop5 = null;
		try {
			prizeTop5 = drawDouble11Dao.getDouble11PrizeRecordTop5();
		} catch (Exception e) {
			e.printStackTrace();
			throw ExceptionBuilder.buildException("093", "当前系统繁忙，请稍后再试", e);
		}
		return prizeTop5;
	}

}
